package tom.reactor.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tom.reactor.dao.UserDao;
import tom.reactor.model.User;

/**
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class UserService {
    @Autowired
    private UserDao dao;

    public Mono<User> save(User user) {
        //保存，当没有用户id, name已存在时可能冲突,此时获取已存在的用户设置id,更新原来用户信息
        return this.dao.save(user)
                .onErrorResume(
                        e -> this.dao.findByName(user.getName())
                        .flatMap(originUser -> {
                            log.warn("user without id : {}, original user : {}", user, originUser);
                            user.setId(originUser.getId());
                            return dao.save(user);
                        })
                );
    }

    public Mono<User> findByName(String name) {
        return this.dao.findByName(name);
    }

    public Mono<User> findById(Long id) {
        return this.dao.findById(id);
    }

    public Flux<User> findAll() {
        return this.dao.findAll();
    }

    public Mono<Void> deleteById(Long id) {
        return this.dao.deleteById(id);
    }
}
